package cn.edu.flink.tutorial.window;

import cn.edu.flink.tutorial.source.UDSourceFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.windows.GlobalWindow;

public class CountWindow {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStreamSource<Long> streamSource = env.addSource(new UDSourceFunction());

        DataStream<Tuple2<Long, Long>> mapedOutput = streamSource.disableChaining()
                .map(new MapFunction<Long, Tuple2<Long, Long>>() {
                    @Override
                    public Tuple2<Long, Long> map(Long integer) throws Exception {
                        return new Tuple2<>(integer, 1L);
                    }
                });

        KeyedStream<Tuple2<Long, Long>, Object> keyedOutput = mapedOutput.keyBy(x -> x.f0);

        WindowedStream<Tuple2<Long, Long>, Object, GlobalWindow> countWindowedOutput = keyedOutput.countWindow(3);

        DataStream<Tuple2<Long, Long>> sum = countWindowedOutput.sum(1);

        sum.print();

        env.execute();
    }
}
